#File: python_functions.py - Auxiliary python functions
#JGordon & Co
from rondamon import RondamonException
from math import floor,ceil
import _mysql
import urllib

def r_concat(args,table):
    if len(args) != 2:
        raise RondamonException("strconcat() takes exactly 2 arguments")
    return str(args[0]) + str(args[1])

def r_extend(args,table):
    if len(args) != 2:
        raise RondamonException("extend() takes exactly 2 arguments")
    args[0].extend(args[1])

def r_pow(args,table):
    if len(args) != 2:
        raise RondamonException("pow() takes exactly 2 arguments")
    if not isinstance(args[0], int) and not isinstance(args[1], int):
        raise RondamonException("pow(): two numbers expected")
    return pow(args[0],args[1])

def r_mod(args,table):
    if len(args) != 2:
        raise RondamonException("mod() takes exactly 2 arguments")
    if not isinstance(args[0], int) and not isinstance(args[1], int):
        raise RondamonException("mod(): two numbers expected")
    return (args[0]%args[1])

def r_isnumber(args,table):
    if len(args) != 1:
        raise RondamonException("isnumber() takes exactly 1 argument")
    return isinstance(args[0], int) or isinstance(args[0], float)

def r_isstring(args,table):
    if len(args) != 1:
        raise RondamonException("isstring() takes exactly 1 argument")
    return isinstance(args[0], str)

def r_tostring(args,table):
    if len(args) != 1:
        raise RondamonException("tostring() takes exactly 1 argument")
    return str(args[0])

def r_tonumber(args,table):
    if len(args) != 1:
        raise RondamonException("tonumber() takes exactly 1 argument")
    return int(args[0])

def r_ceil(args,table):
    if len(args) != 1:
        raise RondamonException("ceil() takes exactly 1 argument")
    return ceil(args[0])

def r_floor(args,table):
    if len(args) != 1:
        raise RondamonException("floor() takes exactly 1 argument")
    return floor(args[0])

def r_append(args,table):
    if len(args) != 2:
        raise RondamonException("append() takes exactly 2 arguments")
    if not isinstance(args[0], list):
        raise RondamonException("append(): first parameter must be a list")
    args[0].append(args[1])

def r_insert(args,table):
    if len(args) != 3:
        raise RondamonException("insert() takes exactly 3 arguments")
    if not isinstance(args[0], list):
        raise RondamonException("insert(): first parameter must be a list")
    args[0].insert(args[1],args[2])

def r_remove(args,table):
    if len(args) != 2:
        raise RondamonException("remove() takes exactly 2 arguments")
    if not isinstance(args[0], list):
        raise RondamonException("remove(): first parameter must be a list")
    args[0].remove(args[1])

def r_sort(args,table):
    if len(args) != 1:
        raise RondamonException("sort() takes exactly 1 argument")
    if not isinstance(args[0], list):
        raise RondamonException("sort(): list expected")
    args[0].sort()

def r_reverse(args,table):
    if len(args) != 1:
        raise RondamonException("reverse() takes exactly 1 argument")
    if not isinstance(args[0], list):
        raise RondamonException("reverse(): list expected")
    args[0].reverse()

def r_pop(args,table):
    if len(args) != 1:
        raise RondamonException("pop() takes exactly 1 argument")
    if not isinstance(args[0], list):
        raise RondamonException("pop(): list expected")
    return (args[0]).pop()

def r_index(args,table):
    if len(args) != 2:
        raise RondamonException("index() takes exactly 2 arguments")
    if not isinstance(args[0], list):
        raise RondamonException("index(): first parameter must be a list")
    if not isinstance(args[1], int):
        raise RondamonException("index(): second paramenter must be an integer")
    return (args[0]).index(args[1])

def r_max(args,table):
    if len(args) != 1:
        raise RondamonException("max() takes exactly 1 argument")
    if not isinstance(args[0], list):
        raise RondamonException("max(): list expected")
    return max(args[0])

def r_min(args,table):
    if len(args) != 1:
        raise RondamonException("min() takes exactly 1 argument")
    if not isinstance(args[0], list):
        raise RondamonException("min(): list expected")
    return min(args[0])

def r_pwebstring(args,table):
    nstring = urllib.unquote_plus(args[0])
    return nstring.replace('\r\n','<br>')
    

def r_escapeHTML(args,table):
    contenido = args[0].replace(chr(60),"&#60;") #<
    contenido = contenido.replace(chr(62),"&#62;") #>
    contenido = contenido.replace(chr(38),"&#38;") #&
    contenido = contenido.replace(chr(39),"&#39;") #'
    contenido = contenido.replace(chr(34),"&#34;") #"
    return contenido

################parameter functions #######################
def r_get_parameter_value(args,table):
    variables = table['parameters']
    for i in variables:
        varcom, value = i.split('=')
        if(varcom == args[0]):
            return value
    return 0

def r_get_parameter_values(args,table):
     variables = table['parameters']
     vlist = []
     for i in variables:
        varcom, value = i.split('=')
        if(varcom == args[0]):
            vlist.append(value)
     return vlist

def r_get_parameter_names(args,table):
     variables = table['parameters']
     parameterlist = []
     for i in variables:
        varcom, value = i.split('=')
        if varcom not in parameterlist:
            parameterlist.append(varcom)
     return parameterlist

#################header functions########################
def r_get_header_value(args,table):
    headers = table['headers']
    for i in headers:
        varcom, value = i.split(': ')
        if(varcom == args[0]):
            return value
    return 0

def r_get_header_names(args,table):
    headers = table['headers']
    headerlist = []
    for i in headers:
        varcom, value = i.split(': ')
        if varcom not in headerlist:
            headerlist.append(varcom)
    return headerlist

def r_set_header_value(args,table):
    table['new_headers'].append(args[0] + ': ' + args[1])

################sessions##################################

def r_get_session_value(args,table):
    session_id = table['session']
    session_dict = table['Sessions'][session_id]
    return session_dict.get(args[0],0)

def r_set_session_value(args,table):
    session_id = table['session']
    session_dict = table['Sessions'][session_id]
    session_dict[args[0]] = args[1]


#################persistence ##############################
try:
    db=_mysql.connect("localhost","juan","paulina","rondamon")
except Exception,E:
    print "Cannot connect to local MySQL server. Persistence will not be available"

def r_get_persistent(args,table):
    query = """SELECT item FROM global WHERE llave = '%s'""" % args[0]
    try :
        db.query(query)
        rslt = db.store_result()
        rtuple = rslt.fetch_row()
        if rtuple:
            return eval(rtuple[0][0])
        else:
            return 0
    except Exception,e:
        print 'An eror ocurred while retrieving data from the database: %s' % e


def r_set_persistent(args,table):
    if not isinstance(args[1],list):
        lst = [args[1]]
    else:
        lst = args[1]
    query = '''insert into global values ("%s","%s") on duplicate key update item= "%s" ''' % (args[0],str(lst),str(lst));
    try :
        db.query(query)
    except Exception,e:
        print 'An eror ocurred while inserting data into the database: %s' % e
